<template>
<div class="user-index">
  <div>
    <!-- 搜索栏 -->
    <div  class="search">
      <el-button  @click="authListFalg = true" style="float: right;margin-top: 10px;margin-right: 50px;" type="primary">查看权限列表</el-button>
      <el-button  @click="saveUser" style="float: right;margin-top: 10px;margin-right: 50px;" type="primary">添加新用户</el-button>
      <ul>
        <li>
          <el-input placeholder="请输入内容" v-model="params.key" clearable width="200">
            <el-button slot="append" icon="el-icon-search" @click="getUserTableData"></el-button>
          </el-input>
        </li>
        <li >
          <el-select v-model="params.sex"  :placeholder="'性别'" @change="getUserTableData">
            <el-option :label="'男'" value="0"></el-option>
            <el-option :label="'女'" value="1"></el-option>
            <el-option :label="'不限'" value=""></el-option>
          </el-select>
        </li>
        <li >
          <el-select v-model="params.status"  :placeholder="'状态'" @change="getUserTableData">
            <el-option :label="'可用'" value="0"></el-option>
            <el-option :label="'不可用'" value="1"></el-option>
            <el-option :label="'不限'" value=""></el-option>
          </el-select>
        </li>

      </ul>




    </div>
<!--    数据-->
    <el-table :data="userTableData"  style="width: 97%" height="800" @sort-change="sortChange">

      <el-table-column fixed prop="avatarId" label="头像" width="80">
        <template slot-scope="scope">
          <el-image shape="circle" :src="'/api/user/download/'+scope.row.avatarId" style="width: 50px; height: 50px" fit="fit"></el-image>
        </template>
      </el-table-column>
      <el-table-column fixed prop="id" label="ID" width="120">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.id" placement="bottom" effect="light">
<!--            <el-button>Light</el-button>-->
            <span>{{scope.row.id.substring(0,10)}}</span>

          </el-tooltip>

        </template>
      </el-table-column>
      <el-table-column fixed prop="username" label="用户名" width="120" sortable="custom">
        <template slot-scope="scope">
          <a href="javascript:void(0)" @click="$router.push('/main/user/detail/'+scope.row.id)">
          <span style="color: #c177e7">{{scope.row.username}}</span>
          </a>

        </template>

      </el-table-column>
      <el-table-column fixed prop="auth" label="权限" width="120" >
        <template slot-scope="scope">
            <span v-if="scope.row.auths[0].code=='0-Root'" style="color: #c177e7">超级管理员</span>
          <span v-else-if="scope.row.auths[0].code=='1-Administrator'" style="color: #c9ade7">管理员</span>
          <span v-else-if="scope.row.auths[0].code=='2-Client'">普通用户</span>
          <span v-else style="color: grey">未知</span>
        </template>

      </el-table-column>
      <el-table-column
          prop="phone"
          label="手机号"
          width="120">
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          width="200">
      </el-table-column>
      <el-table-column prop="address" label="性别" width="80" >
        <template slot-scope="scope">
          <span v-if="scope.row.sex==0">男</span>
          <span v-else-if="scope.row.sex==1">女</span>
          <span v-else style="color: #9f9f9f">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.status==0" style="color: #25bb9b">可用</span>
          <span v-else-if="scope.row.status==1" style="color: #afafaf"> 不可用</span>
          <span v-else style="color: red;"></span>
        </template>
      </el-table-column>
      <el-table-column prop="rating" label="Rating" width="120" sortable="custom">
        <template slot-scope="scope">
          <span v-if="scope.row.rating>=2000" style="color: red">{{ scope.row.rating }}</span>
          <span v-else-if="scope.row.rating>=1000" style="color: #c177e8"> {{ scope.row.rating }}</span>
          <span v-else style="color: #ffd799;"> {{ scope.row.rating }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="school"
          label="学校"
          width="150">
      </el-table-column>
      <el-table-column
          prop="course"
          label="专业"
          width="150">
      </el-table-column>
      <el-table-column
          prop="number"
          label="学号"
          width="150">
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="150" sortable="custom">
        <template slot-scope="scope">
          <span style="color: #8e99a1">{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="150" sortable="custom">
        <template slot-scope="scope">
          <span style="color: #8e99a1">{{scope.row.updateTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="description"
          label="个人说明"
          width="250">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="120">
        <template slot-scope="scope">
          <el-button @click="deleteUser(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
          <el-button type="text" size="small" @click="updateUser(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="setAuthUp(scope.row)" style="color: #2ebe9f;">权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="page">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="params.size"
          :page-sizes="[10,20,30,50,100]"
          @current-change="chg"
          @size-change="chgsize"
      >
      </el-pagination>
    </div>
  </div>

<!--  用户添加/修改 弹出框/表单-->
  <el-drawer
      :title="userDetail.id?'修改用户':'添加一个用户'" :visible.sync="drawer" :direction="'rtl'" :before-close="handleClose">

    <el-form ref="form" :model="userDetail" label-width="80px" >
      <el-input v-model="userDetail.id" v-show="false" disabled></el-input>
      <el-form-item :label="'用户名'" required style="width: 400px;">
        <el-input v-model="userDetail.username"></el-input>
      </el-form-item>
      <el-form-item :label="'密码'" style="width: 400px;">
        <el-input v-model="userDetail.password" ></el-input>
      </el-form-item>
      <el-form-item :label="'手机号'" style="width: 400px;">
        <el-input v-model="userDetail.phone" ></el-input>
      </el-form-item>
      <el-form-item :label="'邮箱'" style="width: 400px;">
        <el-input v-model="userDetail.email" ></el-input>
      </el-form-item>
      <el-form-item :label="'状态'" required style="width: 250px;">
        <el-radio-group v-model="userDetail.status">
          <el-radio :label="0">可用</el-radio>
          <el-radio :label="1">不可用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="'性别'" required style="width: 200px;">
        <el-radio-group v-model="userDetail.sex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="'学校'" style="width: 400px;">
        <el-input v-model="userDetail.school" ></el-input>
      </el-form-item>
      <el-form-item :label="'专业'" style="width: 400px;">
        <el-input v-model="userDetail.course" ></el-input>
      </el-form-item>
      <el-form-item :label="'学号'" style="width: 400px;">
        <el-input v-model="userDetail.number" ></el-input>
      </el-form-item>
      <el-form-item :label="'个人说明'" style="width: 400px;">
        <el-input type="textarea" v-model="userDetail.description" ></el-input>
      </el-form-item>
      <!-- 上传头像 -->
      <el-form-item label="头像" style="width: 200px;">
        <el-image shape="circle" :src="'/api/user/download/'+userDetail.avatarId" style="width: 150px; height: 150px" fit="fit" @click="$refs.ImageFile.click()"></el-image>
        <!-- <el-input v-model="inputFile" placeholder="请输入内容" type="file" style="width:230px;"></el-input> -->
        <input type="file" ref="ImageFile" accept="image/*" @change="getImageFile" style="display: none">
<!--        <span style="margin-left: 10px;color: #bfbfbfbf;">文件ID：{{ formData.fileId }}</span>-->
      </el-form-item>



    </el-form>
    <el-button type="success" plain @click="updateOrSave">{{$t('save')}}</el-button>

  </el-drawer>

<!--  用户快速分配权限-->
  <el-dialog title="快速分配" :visible.sync="dialogFormVisible" >
    <div style="text-align: left">
      <el-select v-model="newAuths" placeholder="设置角色" style="width: 400px;">
        <el-option v-for="item in retainAuth" :key="item.id" :label="item.name+'--'+item.code" :value="item.id"></el-option>
      </el-select>
      <el-button type="primary" @click="dialogFormVisible = false;setAuth();" style="margin-left: 50px;">{{ $t('save') }}</el-button>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">{{ $t('cancel') }}</el-button>
      <el-button @click="dialogFormVisible = false;setAPIAuthUp()">分配API权限</el-button>
    </div>
  </el-dialog>


<!--  api权限分配弹出狂-->
  <el-dialog title="API权限分配" :visible.sync="dialogAPIVisible" >
    <div style="text-align: left">
      <el-select v-model="newAuths" placeholder="分配API" multiple  style="width: 95%;">
        <el-option v-for="item in APIAuths" :key="item.id" :label="item.name+'--'+item.code" :value="item.id"></el-option>
      </el-select>

    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogAPIVisible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dialogAPIVisible = false;setAPIAuth();" style="margin-left: 50px;">{{ $t('save') }}</el-button>
    </div>
  </el-dialog>

<!--  权限列表弹出狂-->
  <el-dialog title="API权限分配" :visible.sync="authListFalg" >
    <AuthList></AuthList>
  </el-dialog>
</div>
</template>

<script>
import * as userApi from '@/api/admin.js'
import * as authApi from "@/api/auth.js";
import {mavonEditor} from "mavon-editor";
// import {} from '@/components/users/auth.vue'
export default {
  name: "userIndex",
  components:{
    AuthList: () => import('@/components/users/auth.vue'),
  },
  data() {
    return {
      drawer: false, //修改/保存用户弹出框
      total:0,
      newAuths:[],
      params:{
        key:"",
        page:1,
        size:10,
      },
      userDetail:{},
      userTableData:[],
      dialogFormVisible:false,
      dialogAPIVisible:false,
      authListFalg:false,
      retainAuth:[],//保留权限
      APIAuths:[], //非保留权限

      // imageFile:{},// 上传图片文件
    };
  },
  methods:{
    getRetainAuth(){  //获取保留权限
      authApi.getAuthList({"status":2}).then(res=>{
        if(res.data.success)this.retainAuth = res.data.data;
      })
    },
    getAuth(){  //获取非保留权限
      authApi.getAuthList({"status":0}).then(res=>{
        if(res.data.success)this.APIAuths = res.data.data;
      })
    },
    setAuth(){
      // console.info(this.newAuths);
      authApi.distributionAuth({"userId":this.userDetail.id,"auths":this.newAuths,"status":2}).then(res=>{
        if(res.data.success) {
          this.$message("修改成功");
          this.dialogFormVisible = false;
        }
      });
    },
    setAPIAuth(){
      authApi.distributionAuth({"userId":this.userDetail.id,"auths":this.newAuths,"status":0}).then(res=>{
        if(res.data.success) {
          this.$message("分配成功");
          this.dialogFormVisible = false;
        }
      });
    },
    setAPIAuthUp(){//修改API权限弹窗
      this.newAuths = [];
      authApi.getAuthList({"userId":this.userDetail.id,"status":0}).then(res=>{
        if(res.data.data){
          for(var i = 0;i<res.data.data.length;i++){
            this.newAuths.push(res.data.data[i].id)
          }
          // this.newAuths = ;
          // console.info(this.newAuths)
        }
      })
      this.dialogAPIVisible = true;

    },
    setAuthUp(data){  //修改权限弹窗
      this.userDetail = data;
      // console.info(data)
      authApi.getAuthList({"userId":data.id,"status":2}).then(res=>{
          if(res.data.data){
            this.newAuths = res.data.data[0].id;
            // console.info(this.newAuths)
          }
        })

      this.dialogFormVisible = true;
    },
    // 自定义排序
    sortChange(column,prop,order){
      // console.info(column);
      this.params.field = column.prop;
      this.params.order = column.order;
      if(this.params.order){
        if(this.params.order[0]=='a')this.params.order = "asc";
        else this.params.order = "desc";
      }else{  this.params.order = "";this.params.field = ''}
      // console.info(this.params)
      this.getUserTableData();
    },
    updateOrSave(){
      if(this.userDetail.id){ //修改
        userApi.updateUserById(this.userDetail).then(res=>{
          if(res.data.success){
            this.$message("修改成功");
            this.drawer = false;
          }
        })
      }else{
        userApi.addUser(this.userDetail).then(res=>{
          if(res.data.success){
            this.$message("保存成功");
            this.drawer = false;
          }
        })
      }
    },
    //获取图片文件
    async getImageFile(event){
      // console.info(event.target.files);
      if(event.target.files[0]&&event.target.files[0].name){
        var imageFile = event.target.files[0];
        // this.problemFileName  = event.target.files[0].name;
        // this.uploadFileFlag = true;
        let form = new FormData();
        form.append('file', imageFile);
        //上传图片
        const res = await userApi.uploadImage(form).then(res=>{
          return res.data.data;
        })
        this.userDetail.avatarId = res;
        this.userDetail = JSON.parse(JSON.stringify(this.userDetail))
        // console.info(this.userDetail);
      }
      // if(event.target.files[1])this.outputFile = event.target.files[1].name;
    },
    //弹出修改狂
    updateUser(data){ //修改
      this.userDetail = data;
      this.drawer = true;
    },
    saveUser(){
      this.userDetail = {"status":0,sex:0};
      this.drawer = true;
    },
    deleteUser(data){ //删除
      this.$confirm(this.$t('problemMode.case.deleteWarnBefore')+this.$t('user')+' '+data.username+this.$t('problemMode.case.deleteWarnAfter'), this.$t('prompt'), {
        confirmButtonText: this.$t('save'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        userApi.deleteUserById({"id":data.id}).then(res=>{
          if(res.data.success){
            this.$message({ type: 'success', message: '删除成功!' });
          }
        })
      })
    },
    handleClose(done) {
      this.$confirm('取消本次修改？', this.$t('prompt'), {
        confirmButtonText: this.$t('save'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(_ => {
            done();
          }).catch(_ => {});
    },

    //每页记录数发生改变时
    chgsize(pgsize) {
      //更改每页记录数
      this.params.size = pgsize;
      //从每一页开始查询
      this.params.page = 1;
      //重新查询
      this.getUserTableData();
    },
    //当页数发生变化时执行
    chg(curpage) {
      //更新查询的页数
      this.params.page = curpage;
      //重新查询
      this.getUserTableData();
    },
    getUserTableData(){
      userApi.getUserList(this.params).then(res=>{
        if(res.data.success){
          this.userTableData = res.data.data.dataList;
          this.total = res.data.data.total;
        }
      })
    }
  },
  created() {
    this.getUserTableData();
    this.getRetainAuth();
    this.getAuth();
  }
}
</script>

<style scoped>
.search > ul > li{
  list-style: none;
  display:inline-block;
  text-align: left;
  width: 15.625rem;
  margin: .625rem;
}
.search > ul{
  /* margin: .625rem; */
  padding: 0px;
  /* margin: 0px; */
  margin-bottom: 20px;
  text-align: left;
  /* width: 55rem; */
}
</style>
